#include <iostream>
#include <pthread.h>
#include <unistd.h>

int cnt = 0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void *Count(void *args)
{
    pthread_detach(pthread_self());   //自己把自己分离，不用在join了

    uint64_t number = (uint64_t)args;
    std::cout<<"pthread: "<<number<<" create successs"<<std::endl;

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);  //pthread_cond_wait让线程等待的时候，会自动释放锁
        std::cout<<"pthread: "<<number<<" , cnt:  "<<cnt++<<std::endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    for (uint64_t i = 0; i < 5; i++) // uint64_t==unsigned long int
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);
        usleep(1000);  //让线程创建有点间隔，去排队的时候能够按顺序排
    }
    sleep(3);
    std::cout<<"main thread ctrl begin: "<<std::endl;

    while(true) 
    {
        sleep(1);
        //pthread_cond_signal(&cond);   //唤醒在cond该条件变量下的等待队列中的一个线程，默认是第一个
        pthread_cond_broadcast(&cond);  //唤醒在cond该条件变量下的等待队列中的所有线程
        std::cout<<"signal one thread..."<<std::endl;
    } //保证主线程不退

    return 0;
}